# -*- coding: utf-8 -*-
import time
import os
import csv
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select, WebDriverWait
from data import bob_dict
from data import ding_sendmsg

#谷歌浏览器无头浏览字段
chrome_op = webdriver.ChromeOptions()  
chrome_op.add_argument('--headless')
chrome_op.add_argument('--disable-gpu')
#火狐浏览器无头浏览字段
firefox_op =webdriver.FirefoxOptions()
firefox_op.add_argument('--headless')
firefox_op.add_argument('--disable-gpu')

class File_dispatch:
    def __init__(self):
        self.gv_ju = 1  # 紧急流程页数指向
        self.gv_jo = 1  # 普通流程页数指向
        self.gv_jf = 1  # 业务分类选择待办页数指向
        self.gv_i = 1  # 流程内FQ序号指向
        self.gv_choose_page = ''
        self.gv_dict_fourdire = bob_dict.gv_dict_fourdire1()
        self.gv_dict = bob_dict.gv_dict1()
        self.gv_department = bob_dict.department()  # 业务部
        self.gv_down = 0  # 在字典中的值,也是后续派工四级目录的位置,与down键对应
        self.gv_choose = ''  # 派工目录表格中的选择项
        self.gv_FQ_send = ''  # 是否派工标记
        self.gv_FQ = ''  # FQ号
        self.gv_FQ_headertxt = ''  # FQ的服务请求描述
        self.gv_FQ_remarks = ''  # fq的备注栏内容
        self.gv_FQ_fourdire = ''  # 四级目录
        self.gv_FQ_time = ''  # 派工时间
        self.gv_FQ_list = []  # 本次运行已派工FQ列表,用于避免重复派工
        self.gv_excel_path = ''  # 当日导出csv路径
        self.gv_refresh_num = 1  # 刷新次数

    def creat_excel(self):  # 打开当天excel,否则创建,写入首行,测量行数,末行写入
        self.gv_excel_path = 'export/' + time.strftime('%Y-%m-%d', time.localtime(time.time())) +self.gv_department +'档案岗派工清单.csv'
        if not os.path.exists(self.gv_excel_path):
            with open(self.gv_excel_path,'w',newline = "") as f:
                w=csv.writer(f,dialect = "excel")
                w.writerow(['是否派工', 'FQ', '抬头文本', '备注详情', '派工岗位', '派工时间'])
        

    def login(self):  # 登录函数,用于登录流程处理
        global gl_driver
        
        # gl_driver = webdriver.Chrome(chrome_options=chrome_op)  # 谷歌无头浏览
        # gl_driver = webdriver.Chrome()

        gl_driver = webdriver.Firefox(firefox_options=firefox_op) #火狐无头浏览
        #gl_driver = webdriver.Firefox()

        gl_driver.maximize_window()
        gl_driver.get("https://fso.sinopec.com")
        if "FSO" in gl_driver.title:
            user = gl_driver.find_element_by_name("j_username")
            user.clear()
            user.send_keys(bob_dict.loginname())
            password = gl_driver.find_element_by_name("j_password")
            password.clear()
            password.send_keys(bob_dict.password(), Keys.ENTER)

        if self.gv_department != '资产':
            try:
                WebDriverWait(gl_driver, 20).until(
                    EC.presence_of_element_located((By.ID, "ZAIC_AG_NJ_4")))
            finally:
                pass
            time.sleep(1)
            gl_driver.find_element_by_id("ZAIC_AG_NJ_4").click()

        try:
            WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                (By.ID, "CRMApplicationFrame")))
        finally:
            pass

    def refresh(self):  # 刷新函数,用于单个流程派工完后的界面刷新
        gl_driver.switch_to.default_content()
        gl_driver.switch_to.frame('CRMApplicationFrame')
        try:
            WebDriverWait(gl_driver, 10).until(
                EC.presence_of_element_located((By.ID, "WorkAreaFrame1")))
        finally:
            pass
        gl_driver.switch_to.frame('WorkAreaFrame1')
        try:
            WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                (By.ID, "C4_W17_V18_IC-MGRHOME")))
        finally:
            pass
        time.sleep(6)
        gl_driver.find_element_by_id(
            "C4_W17_V18_IC-MGRHOME").click()  # 点击待办事项刷新
        time.sleep(6)
        print('\r  ...第%d次刷新页面...' % self.gv_refresh_num, end='')
        self.gv_refresh_num += 1

    def dict1(self):
        '''
        字典函数,用于判定抓取的抬头文本和备注对应的四级目录.
        单个关键词判定, 用'关键词'即可.
        两个关键词判定, 用&符号连接, 即'关键词一&关键词二'表示.
        注意不要在''内出现空格.
        '''
        for key in self.gv_dict.keys():
            if "&" in key:
                list1 = key.split('&')
                if list1[0] in self.gv_FQ_headertxt and list1[1] in self.gv_FQ_headertxt:
                    self.gv_down = self.gv_dict.get(key)
                    break
                else:
                    self.gv_down = 0

            else:
                if key in self.gv_FQ_headertxt:
                    self.gv_down = self.gv_dict.get(key)
                    break
                else:
                    self.gv_down = 0

        if self.gv_down == 0:
            for key in self.gv_dict.keys():
                if "&" in key:
                    list1 = key.split('&')
                    if list1[0] in self.gv_FQ_remarks and list1[1] in self.gv_FQ_remarks:
                        self.gv_down = self.gv_dict.get(key)
                        break
                    else:
                        self.gv_down = 0

                else:
                    if key in self.gv_FQ_remarks:
                        self.gv_down = self.gv_dict.get(key)
                        break

        for key in self.gv_dict_fourdire:
            if key == self.gv_down:
                self.gv_FQ_fourdire = self.gv_dict_fourdire.get(key)
                break
            else:
                self.gv_FQ_fourdire = '未派工, AI判定非'+self.gv_department+'业务'

    def write_excel(self):  # 写入excel函数,一次写入一行
        if self.gv_FQ != '':
            self.gv_FQ_time = time.strftime('%Y-%m-%d %H:%M:%S')
            list1 = [self.gv_FQ_send, self.gv_FQ, self.gv_FQ_headertxt,
                     self.gv_FQ_remarks, self.gv_FQ_fourdire, self.gv_FQ_time]
            with open(self.gv_excel_path,'a', newline = "") as f:
                w=csv.writer(f,dialect = "excel")
                w.writerow(list1)       
            print('\n' + self.gv_FQ + ' ' + self.gv_FQ_headertxt)
            print('  ' + self.gv_FQ_fourdire + '\n  备注:'+self.gv_FQ_remarks)
            msg = self.gv_FQ + ' ' + self.gv_FQ_headertxt + '\n**派工岗位 : ' + \
                self.gv_FQ_fourdire + '\n**备注 : '+self.gv_FQ_remarks
            ding_sendmsg.sendmsg(msg)

    def dispatch_ordinay(self):  # 普通单据流程
        self.gv_i = 1
        gl_driver.switch_to.default_content()
        gl_driver.switch_to.frame('CRMApplicationFrame')
        try:
            WebDriverWait(gl_driver, 10).until(
                EC.presence_of_element_located((By.ID, "WorkAreaFrame1")))
        finally:
            pass
        gl_driver.switch_to.frame('WorkAreaFrame1')
        while True:
            try:
                WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                    (By.ID, "C14_W48_V49_V50_TABLE__header_bee__1")))
            finally:
                pass

            if self.gv_jo != (self.gv_i-1)//10+1:  # 判断当前页码与FQ编号吻合
                self.gv_jo = (self.gv_i-1)//10+1  # 用于取得页数
                self.gv_choose_page = 'C14_W48_V49_V50_TABLE_pag_pg-%d' % (
                    self.gv_jo)
                gl_driver.find_element_by_id(
                    self.gv_choose_page).click()
                time.sleep(2)

            self.gv_choose = "C14_W48_V49_V50_result_table[%d].sqcode" % (
                self.gv_i)
            try:
                self.gv_FQ = gl_driver.find_element_by_id(self.gv_choose).text
            except:
                raise ValueError
           
            self.dispatch()

    def dispatch_ugent(self):  # 紧急单据流程
        self.gv_i = 1
        gl_driver.switch_to.default_content()
        gl_driver.switch_to.frame('CRMApplicationFrame')
        try:
            WebDriverWait(gl_driver, 10).until(
                EC.presence_of_element_located((By.ID, "WorkAreaFrame1")))
        finally:
            pass

        gl_driver.switch_to.frame('WorkAreaFrame1')
        while True:
            try:
                WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                    (By.ID, "C15_W53_V54_V55_TABLE__header_bee__1")))
            finally:
                pass

            if self.gv_ju != (self.gv_i-1)//10+1:
                self.gv_ju = (self.gv_i-1)//10+1
                self.gv_choose_page = 'C15_W53_V54_V55_TABLE_pag_pg-%d' % (
                    self.gv_ju)
                gl_driver.find_element_by_id(
                    self.gv_choose_page).click()
                time.sleep(2)  # 翻页后调整

            self.gv_choose = 'C15_W53_V54_V55_result_table[%d].sqcode' % (
                self.gv_i)
            try:
                self.gv_FQ = gl_driver.find_element_by_id(self.gv_choose).text
            except:
                raise ValueError
            self.dispatch()

    def dispatch_first(self):  # 业务分类选择待办流程
        self.gv_i = 1
        gl_driver.switch_to.default_content()
        gl_driver.switch_to.frame('CRMApplicationFrame')
        try:
            WebDriverWait(gl_driver, 10).until(
                EC.presence_of_element_located((By.ID, "WorkAreaFrame1")))
        finally:
            pass

        gl_driver.switch_to.frame('WorkAreaFrame1')
        while True:
            try:
                WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                    (By.ID, "C13_W43_V44_V45_TABLE__header_bee__1")))  # 判定至目标页面
            finally:
                pass

            if self.gv_jf != (self.gv_i-1)//10+1:
                self.gv_jf = (self.gv_i-1)//10+1
                self.gv_choose_page = 'C13_W43_V44_V45_TABLE_pag_pg-%d' % (
                    self.gv_jf)
                gl_driver.find_element_by_id(self.gv_choose_page).click()
                time.sleep(2)  # 翻页后调整

            self.gv_choose = 'C13_W43_V44_V45_result_table[%d].sqcode' % (
                self.gv_i)
            try:
                self.gv_FQ = gl_driver.find_element_by_id(self.gv_choose).text
            except:
                raise ValueError
            self.dispatch()

    def dispatch(self):
        lv_down = ''  # 表示四级目录对应下键次数
        if self.gv_FQ not in self.gv_FQ_list:  # 先判断是否在FQ列表里,用于避免重复操作同一笔FQ
            self.gv_FQ_list.append(self.gv_FQ)
            time.sleep(1)
            gl_driver.find_element_by_id(self.gv_choose).click()  # 点击派工岗FQ

            try:
                WebDriverWait(gl_driver, 10).until(EC.presence_of_element_located(
                    (By.XPATH, '//*[@id="C29_W89_V91_V96_btadminh_struct.description"]')))  # 判定至目标页面
            except:
                raise ValueError

            self.gv_FQ_headertxt = gl_driver.find_element_by_xpath(
                '//*[@id="C29_W89_V91_V96_btadminh_struct.description"]').get_attribute('value')  # 获取服务请求描述

            gl_driver.find_element_by_id('C29_W89_V91_0002_expand_link').click()  # 点击备注

            try:
                WebDriverWait(gl_driver, 5).until(EC.presence_of_element_located((By.XPATH, '//a[contains(@id, "_text_table[1].lines")]')))

                self.gv_FQ_remarks = gl_driver.find_element_by_xpath('//a[contains(@id, "_text_table[2].lines")]').get_attribute('title')
            except:
                pass

            self.dict1()

            if self.gv_department == '总账' and 'FQ-1110' in self.gv_FQ and self.gv_down == 0:  # 如果为1110的单据,且未能派工,则默认派工至一般总账
                self.gv_down = 32

            if self.gv_down != 0:
                gl_driver.find_element_by_id(
                    'C31_W100_V101_btcategoryfirst_cat01').click()
                time.sleep(1)
                gl_driver.find_element_by_id(
                    'C31_W100_V101_btcategoryfirst_cat01').send_keys(Keys.UP, Keys.ENTER)
                time.sleep(2)
                gl_driver.find_element_by_id(
                    'C31_W100_V101_btcategoryfirst_cat01').click()
                time.sleep(1)
                gl_driver.find_element_by_id(
                    'C31_W100_V101_btcategoryfirst_cat01').send_keys(Keys.UP, Keys.ENTER)
                time.sleep(2)
                lv_down = ''

                if self.gv_down > 100:
                    gl_driver.find_element_by_id(
                        'C31_W100_V101_btcategoryfirst_cat03').click()
                    time.sleep(2)
                    lv_down = '\ue015'*(self.gv_down-101)+'\ue007'
                    gl_driver.find_element_by_id(
                        'C31_W100_V101_btcategoryfirst_cat03').send_keys(lv_down)

                if self.gv_down < 100:
                    gl_driver.find_element_by_id(
                        'C31_W100_V101_btcategoryfirst_cat04').click()
                    time.sleep(2)
                    lv_down = '\ue015'*(self.gv_down-1)+'\ue007'
                    gl_driver.find_element_by_id(
                        'C31_W100_V101_btcategoryfirst_cat04').send_keys(lv_down)

                self.gv_FQ_send = "已派工"
                self.write_excel()

                try:
                    WebDriverWait(gl_driver, 10).until(EC.text_to_be_present_in_element_value(
                        (By.ID, "C31_W100_V101_btcategoryfirst_cat02"), '_'))
                finally:
                    pass  # 判定四层级目录已经加载完毕

                time.sleep(2)
                try:
                    gl_driver.find_element_by_xpath('//a[contains(@id, "_SAVE")]').click()  # 点击保存 //*[@id="C29_W89_V91_SAVE"]
                except:
                    print('保存失败')
                self.gv_i = 1
                self.gv_FQ = ''
                self.gv_FQ_remarks = ''
                self.gv_FQ_headertxt = ''
                self.gv_jo = 1
                self.gv_ju = 1
                self.gv_jf = 1
            else:
                self.gv_FQ_send = "未派工"
                self.write_excel()
                gl_driver.find_element_by_id(
                    'C29_W89_V91_#Exit#_CANCEL').click()  # 点击取消
                self.gv_i = 1
                self.gv_FQ = ''
                self.gv_FQ_remarks = ''
                self.gv_FQ_headertxt = ''
                self.gv_jo = 1
                self.gv_ju = 1
                self.gv_jf = 1

        else:  # 对于已在FQ列表中的FQ,跳过操作,进入下一轮循环
            self.gv_i += 1
            self.gv_FQ = ''

    def Main(self):
        self.creat_excel()
        self.login()
        while True:  # 普通流程和紧急流程来回切换
            try:
                self.dispatch_first()
            except:
                pass

            try:
                self.dispatch_ordinay()
            except:
                pass

            try:
                self.dispatch_ugent()
            except:
                pass

            try:
                self.refresh()
            except:
                gl_driver.delete_all_cookies()
                gl_driver.quit()
                self.creat_excel()
                self.gv_refresh_num = 1
                print('\n\n  **********重 启 浏 览 器**********\n\n')
                self.login()

            finally:
                if len(self.gv_FQ_list) >150:
                    self.gv_FQ_list=self.gv_FQ_list[50:]

                if self.gv_refresh_num > 400:
                    gl_driver.delete_all_cookies()
                    gl_driver.quit()
                    self.creat_excel()
                    self.gv_refresh_num = 1
                    print('\n\n  **********重 启 浏 览 器**********\n\n')
                    self.login()


if __name__ == "__main__":
    gl = File_dispatch()
    gl.Main()
